﻿@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using Microsoft.Extensions.Options
@using SimpleIdServer.CredentialIssuer.Startup.Resources;
@using System.Globalization;
@using SimpleIdServer.IdServer.CredentialIssuer
@model SimpleIdServer.CredentialIssuer.UI.ViewModels.CredentialsViewModel

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h3>@Global.ShareCredentialsTitle</h3>
<div class="row">
    @foreach(var credentialConfiguration in Model.CredentialConfigurations)
    {
        var display = credentialConfiguration.Displays.SingleOrDefault(d => d.Locale == CultureInfo.CurrentUICulture.ToString());
        var picture = "/images/wallet.svg";
        var cssStyles = new List<string>
        {
            "overflow:hidden"
        };
        if(display != null)
        {
            if (!string.IsNullOrWhiteSpace(display.LogoUrl)) picture = display.LogoUrl;
            if (!string.IsNullOrWhiteSpace(display.TextColor))
                cssStyles.Add($"color:{display.TextColor}");
            if (!string.IsNullOrWhiteSpace(display.BackgroundColor))
                cssStyles.Add($"background-color:{display.BackgroundColor}");
        }

        var innerCssStyles = string.Join(";", cssStyles);
        var title = display == null ? credentialConfiguration.ServerId : display.Name;

        <div class="col-md-4">
            <form asp-controller="Credentials" asp-action="Share" method="post" class="shareCredentialConfiguration">
                <div class="card" style="@innerCssStyles">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <img src="@picture" style="max-width: 60px;max-height: 60px;" />
                            </div>
                            <div class="col">
                                <h6>@title</h6>
                                @if (display != null)
                                {
                                    <p>@display.Description</p>
                                }
                            </div>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" value="" name="preAuthorized">
                            <label class="form-check-label">
                                @Global.PreAuthorized
                            </label>
                        </div>
                    </div>
                    <div class="card-footer">
                        <input type="hidden" name="configurationId" value="@credentialConfiguration.ServerId" />
                        <button type="submit" class="btn btn-primary shareBtn" href="#">@Global.Share</button>
                    </div>
                </div>
            </form>
        </div>
    }
</div>

<div class="modal fade" id="qrCodeDialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">@Global.ScanQrCodeWithYourWalletApplication</h5>
            </div>
            <div class="modal-body" style="text-align:center;">
                <img style="width: 400px" src="" />
                @if(Model.IsDeveloperModeEnabled)
                {
                    <div class="divider"></div>
                    <div id="qrCodeText">
                        <h3>@Global.QrCode</h3>
                        <textarea class="form-control" rows="5"></textarea>
                    </div>
                }
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary close" data-dismiss="modal">@Global.Close</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="errorDialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">@Global.Error</h5>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary close" data-dismiss="modal">@Global.Close</button>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            const loadingText = "@Global.Loading";
            const shareText = "@Global.Share";
            function displayQrCode(img, qrCode) {
                $("#qrCodeDialog img").attr("src", img);
                $("#qrCodeDialog").modal('toggle');
                var qrCodeText = $("#qrCodeText");
                if(qrCodeText.length > 0) {
                    $("#qrCodeText textarea").val(qrCode);
                }
            }

            function displayError(json) {
                $("#errorDialog .modal-body").html(json["error_description"]);
                $("#errorDialog").modal("toggle");
            }

            async function generateQrCode(url, body, shareBtn) {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(body)
                });

                shareBtn.html(shareText);
                shareBtn.prop('disabled', false);
                if (!response.ok) {
                    const json = await response.json();
                    displayError(json);
                    return;
                }

                const blob = await response.blob();
                const img = URL.createObjectURL(blob);
                const qrCode = response.headers.get('QRCode');
                displayQrCode(img, qrCode);
            }

            $("#errorDialog .close").click(function () {
                $("#errorDialog").modal("toggle");
            });

            $("#qrCodeDialog .close").click(function () {
                $("#qrCodeDialog").modal("toggle");
            });

            $(".shareCredentialConfiguration").submit((e) => {
                e.preventDefault();
                const target = e.target;
                const shareBtn = $(target).find(".shareBtn");
                const configurationId = $(target).find('input[name="configurationId"]').val();
                const preAuthorized = $(target).find('input[name="preAuthorized"]').is(':checked');
                const body = { configurationId: configurationId, preAuthorized: preAuthorized };
                const url = $(target).attr('action');
                shareBtn.html(loadingText);
                shareBtn.prop('disabled', true);
                generateQrCode(url, body, shareBtn);
            });
        });  
    </script>
}